<template>
	<div class="dynamic-search-wrapper">
		<el-card class="search-card" >
			<template #header>
				<div class="card-header">
					<span>高级搜索</span>
					<el-button
						type="text"
						@click="toggleCollapse"
						class="collapse-btn"
					>
						{{ isCollapsed ? '展开' : '折叠' }}
						<el-icon>
							<ArrowDown v-if="isCollapsed" />
							<ArrowUp v-else />
						</el-icon>
					</el-button>
				</div>
			</template>
			<el-form
				ref="searchForm"
				:model="searchForm"
				label-width="100px"
				v-show="!isCollapsed"
			>
				<el-row :gutter="20">
					<el-col
						v-for="(item, index) in searchableColumns"
						:key="index"
						:xs="24" :sm="12" :md="8" :lg="6" :xl="6"
					>
						<el-form-item :label="item.label + ':'" :prop="item.prop">
							<!-- 文本输入框 -->
							<el-input
								v-if="!item.filters"
								v-model="searchForm[item.prop]"
								:placeholder="`请输入${item.label}`"
								clearable
							/>

							<!-- 下拉选择框（针对有 filters 的字段） -->
							<el-select
								v-else
								v-model="searchForm[item.prop]"
								:placeholder="`请选择${item.label}`"
								clearable
								filterable
								style="width: 100%"
							>
								<el-option
									v-for="option in item.filters"
									:key="option.value"
									:label="option.text"
									:value="option.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item class="action-buttons">
					<el-button type="primary" @click="handleSearch">搜索</el-button>
					<el-button @click="resetSearch">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- 这里放置表格或其他内容 -->
		<slot></slot>
	</div>
</template>

<script setup>
import {ref, computed} from 'vue'
import {ArrowDown, ArrowUp} from '@element-plus/icons-vue'

const props = defineProps({
	columns: {
		type: Array,
		required: true
	}
})

const emit = defineEmits(['search'])

// 折叠状态
const isCollapsed = ref(false)

// 搜索表单数据
const searchForm = ref({})

// 初始化搜索表单
const initSearchForm = () => {
	searchForm.value = {}
	props.columns.forEach(col => {
		searchForm.value[col.prop] = ''
	})
}

// 计算属性：筛选可搜索的列（可根据需求定制）
const searchableColumns = computed(() => {
	return props.columns.filter(col => {
		// 这里可以添加其他过滤条件
		return col.label && col.prop
	})
})

// 切换折叠状态
const toggleCollapse = () => {
	isCollapsed.value = !isCollapsed.value
}

// 搜索方法
const handleSearch = () => {
	const params = {}
	// 过滤掉空值
	Object.keys(searchForm.value).forEach(key => {
		if (searchForm.value[key] !== '') {
			params[key] = searchForm.value[key]
		}
	})
	emit('search', params)
}

// 重置搜索
const resetSearch = () => {
	initSearchForm()
	emit('search', {})
}

// 初始化
initSearchForm()
</script>

<style scoped>

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.collapse-btn {
	padding: 0;
}

.action-buttons{
}

</style>
